import $ from 'jquery';
import { Entities,WebUser} from './Gener.js';
import {FrmRBs} from './MyFlowGener.js';
/**
 * 获取页面中复选框的的元素
 */
function GenerCheckNames() {

    var checkBoxNames = "";
    var arrObj = document.all;

    for (var i = 0; i < arrObj.length; i++) {

        if (arrObj[i].type != 'checkbox')
            continue;

        var cid = arrObj[i].name;
        if (cid == null || cid == "" || cid == '')
            continue;
        if (checkBoxNames.indexOf(arrObj[i].name) == -1)
        checkBoxNames += arrObj[i].name + ',';
    }
    return checkBoxNames;
}

/**
 * 初始化下拉列表框的OPERATION
 * @param {表单中的DataSet数据集合} flowData 
 * @param {字段元素属性} mapAttr 
 * @param {默认值} defVal 
 */
function InitDDLOperation(flowData, mapAttr, defVal) {

    var operations = '';
    var data = flowData[mapAttr.KeyOfEn];
    if (data == undefined)
        data = flowData[mapAttr.UIBindKey];
    if (data == undefined) {
        //枚举类型的.
        if (mapAttr.LGType == 1) {
            var enums = flowData.Sys_Enum;
            enums = $.grep(enums, function (value) {
                return value.EnumKey == mapAttr.UIBindKey;
            });


            $.each(enums, function (i, obj) {
                operations += "<option " + (obj.IntKey == mapAttr.DefVal ? " selected='selected' " : "") + " value='" + obj.IntKey + "'>" + obj.Lab + "</option>";
            });
        }
        return operations;
    }
    $.each(data, function (i, obj) {
        operations += "<option " + (obj.No == defVal ? " selected='selected' " : "") + " value='" + obj.No + "'>" + obj.Name + "</option>";
    });
    return operations;
}

/**
 * 填充默认数据
 * @param {表单数据} flowData 
 * @param {默认值} defVal 
 * @param {字段键值} keyOfEn 
 * @param {组件} component
 * 
 */
function ConvertDefVal(mainTable, defVal, keyOfEn) {
    //计算URL传过来的表单参数@TXB_Title=事件测试
    //var pageParamObj = component.$route.params;
    var result = defVal;
    //通过MAINTABLE返回的参数
    for (var ele in mainTable) {
        if (keyOfEn == ele && mainTable != '') {
            result = mainTable[ele];
            break;
        }
    } 
    result = unescape(result);

    if (result == "null")
        result = "";

    return result;
}


/**
 * 必填项检查   名称最后是*号的必填  如果是选择框，值为'' 或者 显示值为 【*请选择】都算为未填 返回FALSE 检查必填项失败
 */
function checkBlanks() {

    var checkBlankResult = true;
    //获取所有的列名 找到带* 的LABEL mustInput
    var lbs = $('.mustInput'); //获得所有的class=mustInput的元素.

    $.each(lbs, function (i, obj) {

        if (!($(obj).parent().css('display') != 'none' && (($(obj).parent().next().css('display')) != 'none' || ($(obj).siblings("textarea").css('display')) != 'none'))) 
            return;
        
        var keyofen = $(obj).data().keyofen;
        var ele = $('[id$=_' + keyofen + ']');
        if (ele.length == 0)
            return;

        $.each(ele, function (i, obj) {
            var eleM = $(obj);
            switch (eleM[0].tagName.toUpperCase()) {
                case "INPUT":
                    if (eleM.attr('type') == "text") {
                        if (eleM.val() == "") {
                            checkBlankResult = false;
                            eleM.addClass('errorInput');
                        } else {
                            eleM.removeClass('errorInput');
                        }
                    }
                    break;
                case "SELECT":
                    if (eleM.val() == "" || eleM.children('option:checked').text() == "*请选择") {
                        checkBlankResult = false;
                        eleM.addClass('errorInput');
                    } else {
                        eleM.removeClass('errorInput');
                    }
                    break;
                case "TEXTAREA":
                    if (eleM.val() == "") {
                        checkBlankResult = false;
                        eleM.addClass('errorInput');
                    } else {
                        eleM.removeClass('errorInput');
                    }
                    break;
            }
        });

    });
    //2.对 UMEditor 中的必填项检查没有做处理
   

    return checkBlankResult;
}
/**
 * 正则表达式检查
 */
function checkReg() {
    var checkRegResult = true;
    var regInputs = $('.CheckRegInput');
    $.each(regInputs, function (i, obj) {
        var name = obj.name;
        var mapExtData = $(obj).data();
        if (mapExtData.Doc != undefined) {
            var regDoc = mapExtData.Doc.replace(/【/g, '[').replace(/】/g, ']').replace(/（/g, '(').replace(/）/g, ')').replace(/｛/g, '{').replace(/｝/g, '}').replace(/，/g, ',');
            var tag1 = mapExtData.Tag1;
            if ($(obj).val() != undefined && $(obj).val() != '') {

                var result = window.CheckRegInput(name, regDoc, tag1);
                if (!result) {
                    $(obj).addClass('errorInput');
                    checkRegResult = false;
                } else {
                    $(obj).removeClass('errorInput');
                }
            }
        }
    });

    return checkRegResult;
}

//记录改变字段样式 不可编辑，不可见
var AllObjSet = {};
/**
 * 下拉框值改变的联动
 * @param {下拉框元素}} obj 
 * @param {表单属性} FK_MapData 
 * @param {字段键值} KeyOfEn 
 * @param {字段多参数字段} AtPara 
 * @param {表单类型} frmType 
 */
window.changeEnable=function(obj, FK_MapData, KeyOfEn, AtPara,frmType) {
    if (AtPara.indexOf('@IsEnableJS=1') >= 0) {
        var selecedval = $(obj).children('option:selected').val();  //弹出select的值.
        cleanAll(KeyOfEn, frmType);
        setEnable(FK_MapData, KeyOfEn, selecedval, frmType);
        $(obj).val(selecedval);
    }
}
/**
 * 单选按钮值改变的联动
 * @param {下拉框元素}} obj 
 * @param {表单属性} FK_MapData 
 * @param {字段键值} KeyOfEn 
 * @param {字段多参数字段} AtPara 
 * @param {表单类型} frmType 
 */
window.clickEnable=function (obj, FK_MapData, KeyOfEn, AtPara, frmType) {
    if (AtPara.indexOf('@IsEnableJS=1') >= 0) {
        var selectVal = $(obj).val();
        cleanAll(KeyOfEn, frmType);
        setEnable(FK_MapData, KeyOfEn, selectVal, frmType);
        document.getElementById("RB_" + KeyOfEn + "_" + selectVal).checked = true
    }
}
/**
 * 复选框值改变的联动
 * @param {下拉框元素}} obj 
 * @param {表单属性} FK_MapData 
 * @param {字段键值} KeyOfEn 
 * @param {字段多参数字段} AtPara 
 * @param {表单类型} frmType 
 */
window.changeCBEnable=function (obj, FK_MapData, KeyOfEn, AtPara, frmType) {
    if (AtPara.indexOf('@IsEnableJS=1') >= 0) {
        cleanAll(KeyOfEn, frmType);
        if (obj.checked == true) {
            setEnable(FK_MapData, KeyOfEn, 1, frmType);
            obj.checked = true;
        }
        else {
            setEnable(FK_MapData, KeyOfEn, 0, frmType);
            obj.checked = false;
        }
           
    }
}

/**
 * 清空改字段的联动设计
 * @param {字段键值} KeyOfEn 
 * @param {表单类型} frmType 
 */
function cleanAll(KeyOfEn, frmType,frmAttrData) {
    var trs = $("#CCForm  table tr .attr-group"); //如果隐藏就显示
    $.each(trs, function (i, obj) {
        if ($(obj).parent().is(":hidden") == true)
            $(obj).parent().show();

    });
    if (AllObjSet.length == 0)
        return;
    if (AllObjSet[KeyOfEn]!=undefined && AllObjSet[KeyOfEn].length > 0) {
        var mapAttrs = AllObjSet[KeyOfEn][0];
        for (var i = 0; i < mapAttrs.length; i++) {
            if (frmType != null && frmType !== undefined && frmType == 8)
                SetDevelopCtrlShow(mapAttrs[i]);
            else
                SetCtrlShow(mapAttrs[i]);
            SetCtrlEnable(mapAttrs[i]);
        }
    }

    if (frmAttrData != undefined && frmAttrData.length != 0) {
        $.each(frmAttrData, function (i, obj) {
            SetCtrlVal(obj.KeyOfEn, obj.Val);
        });

    }
   

}
/**
 * 设置表单联动
 * @param {表单No} FK_MapData 
 * @param {字段键值} KeyOfEn 
 * @param {下拉框、单选按钮、复选框的当前选中的值} selectVal 
 * @param {表单类型} frmType 
 */
function setEnable(FK_MapData, KeyOfEn, selectVal, frmType) {
	if(selectVal==undefined)
        return;

    var pkval = FK_MapData + "_" + KeyOfEn + "_" + selectVal;


    var frmRBs = FrmRBs[0];
    if (frmRBs.length <= 0)
        return;


    var frmRB = null;
    for (var i = 0; i < frmRBs.length; i++) {
        if (frmRBs[i].MyPK == pkval) {
            frmRB = frmRBs[i];
            break;
        }
    }
    if (frmRB == null)
        return;

    var mapAttrs = [];

    //解决字段隐藏显示.
    var cfgs = frmRB.FieldsCfg;

    //解决为其他字段设置值.
    var setVal = frmRB.SetVal;
    if (setVal) {
        var strs = setVal.split('@');

        for ( i = 0; i < strs.length; i++) {

            var str = strs[i];
            if (str == "")
                continue;
            var kv = str.split('=');

            var key = kv[0];
            var value = kv[1];
            SetCtrlVal(key, value);
            mapAttrs.push(key);

        }
    }
    //@Title=3@OID=2@RDT=1@FID=3@CDT=2@Rec=1@Emps=3@FK_Dept=2@FK_NY=3
    if (cfgs) {

        strs = cfgs.split('@');

        for (i = 0; i < strs.length; i++) {

            str = strs[i];
            kv = str.split('=');

            key = kv[0];
            var sta = kv[1];

            if (sta == 0)
                continue; //什么都不设置.


            if (sta == 1) {  //要设置为可编辑.
                if (frmType != null && frmType != undefined && frmType == 8)
                    SetDevelopCtrlShow(key);
                else
                    SetCtrlShow(key);
                SetCtrlEnable(key);
            }

            if (sta == 2) { //要设置为不可编辑.
                if (frmType != null && frmType != undefined && frmType == 8)
                    SetDevelopCtrlShow(key);
                else
                    SetCtrlShow(key);
                SetCtrlUnEnable(key);
                mapAttrs.push(key);
            }

            if (sta == 3) { //不可见.
                if (frmType!=null && frmType!=undefined && frmType == 8)
                    SetDevelopCtrlHidden(key);
                else
                    SetCtrlHidden(key); 

                mapAttrs.push(key);
            }

        }
        if (!$.isArray(AllObjSet[KeyOfEn])) {
            AllObjSet[KeyOfEn] = [];
        }
        AllObjSet[KeyOfEn] = [];
        AllObjSet[KeyOfEn].push(mapAttrs);

    }

    //设置是否隐藏分组、获取字段分组所有的tr 
    var trs = $("#CCForm  table tr .attr-group");
    var isHidden = false;
    $.each(trs, function (i, obj) {
        //获取所有跟随的同胞元素，其中有不隐藏的tr,就跳出循环
        var sibles = $(obj).parent().nextAll();
        for (var k = 0; k < sibles.length; k++) {
            var sible = $(sibles[k]);
            if (sible.find(".attr-group").length > 0 || sible.find(".form-unit").length > 0)
                break;
            if (sible.is(":hidden") == false) {
                isHidden = false;
                break;
            }
            isHidden = true;
        }
        if (isHidden == true)
            $(obj).parent().hide();

    });


}

/**
 * 设置字段可编辑
 * @param {字段键值} key 
 */
function SetCtrlEnable(key) {

    var ctrl = $("#TB_" + key);
    if (ctrl.length > 0) {
        ctrl.removeAttr("disabled");
        ctrl.addClass("form-control");
    }

    ctrl = $("#DDL_" + key);
    if (ctrl.length > 0) {
        ctrl.removeAttr("disabled");
        ctrl.addClass("form-control");
    }

    ctrl = $("#CB_" + key);
    if (ctrl.length > 0) {
        ctrl.removeAttr("disabled");
//        ctrl.addClass("form-control");
    }

    ctrl = document.getElementsByName('RB_' + key);
    if (ctrl != null && ctrl.length !=0 ) {

        var ses = new Entities("BP.Sys.SysEnums");
        ses.Retrieve("EnumKey", key);


        for (var i = 0; i < ses.length; i++)
            $("#RB_" + key + "_" + ses[i].IntKey).removeAttr("disabled");
    }
}
/**
 * 设置字段不可编辑
 * @param {字段键值}} key 
 */
function SetCtrlUnEnable(key) {

    var ctrl = $("#TB_" + key);
    if (ctrl.length > 0) {
        ctrl.attr("disabled", "true");
        ctrl.removeClass("form-control");
    }

    ctrl = $("#DDL_" + key);
    if (ctrl.length > 0) {
        ctrl.attr("disabled", "disabled");
        ctrl.removeClass("form-control");
    }

    ctrl = $("#CB_" + key);
    if (ctrl.length > 0) {

        ctrl.attr("disabled", "disabled");
        ctrl.removeClass("form-control");
    }

    ctrl = $("#RB_" + key);
    if (ctrl != null) {
        $('input[name=RB_' + key + ']').attr("disabled", "disabled");

    }
}
/**
 * 设置字段隐藏
 * @param {字段键值} key 
 */
function SetCtrlHidden(key) {
    ctrl = $("#Lab_" + key);
    if (ctrl.length > 0)
        ctrl.parent('tr').hide();

    var ctrl = $("#Td_" + key);
    if (ctrl.length > 0) {
        ctrl.parent('tr').hide();
    }


}
/**
 * 设置字段显示
 * @param {字段键值} key 
 */
function SetCtrlShow(key) {
    var ctrl = $("#Td_" + key);
    if (ctrl.length > 0) {
        ctrl.parent('tr').show();
    }

    ctrl = $("#Lab_" + key);
    if (ctrl.length > 0) {
        ctrl.parent('tr').show();
    }


}


/**
 * 设置开发者表单字段隐藏
 * @param {字段键值} key 
 */
function SetDevelopCtrlHidden(key) {
    var ctrl = $("#TB_" + key);
    if (ctrl.length > 0) {
        ctrl.hide();
    }

    ctrl = $("#DDL_" + key);
    if (ctrl.length > 0) {
        ctrl.hide();
    }

    ctrl = $("#CB_" + key);
    if (ctrl.length > 0) {
        ctrl.hide();
        if (ctrl.parent() != undefined && ctrl.parent().length > 0) {
            if ($(ctrl.parent()[0]).context.nodeName.toLowerCase() == "label")
                $(ctrl.parent()[0]).hide();
        }
      
    }

    ctrl = $("#SR_" + key);
    if (ctrl.length > 0) {
        ctrl.hide();
    }

    ctrl = $("#SC_" + key);
    if (ctrl.length > 0) {
        ctrl.show();
    }

    ctrl = $("#Lab_" + key);
    if (ctrl.length > 0) {
        ctrl.hide();
    }

    CleanCtrlVal(key);


}
/**
 * 设置开发者表单字段显示
 * @param {字段键值} key 
 */
function SetDevelopCtrlShow(key) {
    var ctrl = $("#TB_" + key);
    if (ctrl.length > 0) {
        ctrl.show();
    }

    ctrl = $("#DDL_" + key);
    if (ctrl.length > 0) {
        ctrl.show();
    }

    ctrl = $("#CB_" + key);
    if (ctrl.length > 0) {
        ctrl.show();
        if (ctrl.parent() != undefined && ctrl.parent().length > 0) {
            if ($(ctrl.parent()[0]).context.nodeName.toLowerCase() == "label")
                $(ctrl.parent()[0]).show();
        }
    }

    ctrl = $("#SR_" + key);
    if (ctrl.length > 0) {
        ctrl.show();
    }

    ctrl = $("#SC_" + key);
    if (ctrl.length > 0) {
        ctrl.show();
    }

    ctrl = $("#Lab_" + key);
    if (ctrl.length > 0) {
        ctrl.show();
    }
}

//设置值?
function SetCtrlVal(key, value) {
    var ctrl = $("#TB_" + key);
    if (ctrl.length > 0) {
        ctrl.val(value);
    }

    ctrl = $("#DDL_" + key);
    if (ctrl.length > 0) {
        ctrl.val(value);
    }

    ctrl = $("#CB_" + key);
    if (ctrl.length > 0) {
        ctrl.val(value);
        ctrl.attr('checked', true);
    }

    ctrl = $("#RB_" + key + "_" + value);
    if (ctrl.length > 0) {
        var checkVal = $('input:radio[name=RB_' + key + ']:checked').val();
        document.getElementById("RB_" + key + "_" + checkVal).checked = false;
        document.getElementById("RB_" + key + "_" + value).checked = true;
        // ctrl.attr('checked', 'checked');
    }
}

//清空值?
function CleanCtrlVal(key) {
    var ctrl = $("#TB_" + key);
    if (ctrl.length > 0) {
        ctrl.val('');
    }

    ctrl = $("#DDL_" + key);
    if (ctrl.length > 0) {
        //ctrl.attr("value",'');
        ctrl.val('');
        // $("#DDL_"+key+" option:first").attr('selected','selected');
    }

    ctrl = $("#CB_" + key);
    if (ctrl.length > 0) {
        ctrl.attr('checked', false);
    }

    ctrl = $("#RB_" + key + "_" + 0);
    if (ctrl.length > 0) {
        ctrl.attr('checked', true);
    }
}

/**
 * 设置下拉框的options
 * @param {下拉框的ID} ddlCtrlID 
 * @param {下拉框的option数据} data 
 * @param {key} noCol 
 * @param {Lab值} nameCol 
 * @param {选中的值} selectVal 
 * @param {过滤键值1} filterKey1 
 * @param {过滤value} filterVal1 
 */
function GenerBindDDL(ddlCtrlID, data, noCol, nameCol, selectVal, filterKey1, filterVal1) {

    if (noCol == null)
        noCol = "No";

    if (nameCol == null)
        nameCol = "Name";

    //判断data是否是一个数组，如果是一个数组，就取第1个对象.
    var json = data;

    // 清空默认值, 写一个循环把数据给值.
    $("#" + ddlCtrlID).empty();
    $("#" + ddlCtrlID).append("<option value=''>- 请选择 -</option>");

    //如果他的数量==0，就return.
    if (json.length == 0)
        return;

    if (data[0].length == 1)
        json = data[0];

    if (json[0][noCol] == undefined) {
        alert('@在绑定[' + ddlCtrlID + ']错误，No列名' + noCol + '不存在,无法行程期望的下拉框value . ');
        return;
    }

    if (json[0][nameCol] == undefined) {
        alert('@在绑定[' + ddlCtrlID + ']错误，Name列名' + nameCol + '不存在,无法行程期望的下拉框value. ');
        return;
    }

    for (var i = 0; i < json.length; i++) {

        if (filterKey1 != undefined) {
            if (json[i][filterKey1] != filterVal1)
                continue;
        }

        if (json[i][noCol] == undefined)
            $("#" + ddlCtrlID).append("<option value='" + json[i][0] + "'>" + json[i][1] + "</option>");
        else
            $("#" + ddlCtrlID).append("<option value='" + json[i][noCol] + "'>" + json[i][nameCol] + "</option>");
    }

    //设置选中的值.
    var v="";
    if (selectVal != undefined) {

        v = $("#" + ddlCtrlID)[0].options.length;
        if (v == 0)
            return;

        $("#" + ddlCtrlID).val(selectVal);

        v = $("#" + ddlCtrlID).val();
        if (v == null) {
            $("#" + ddlCtrlID)[0].options[0].selected = true;
        }
    }
}

//表达式的替换.
function DealExp(expStr, webUser) {

    if (expStr.indexOf('@') == -1)
        return expStr;

    if (webUser == null || webUser == undefined)
        webUser = new WebUser();

    //替换表达式常用的用户信息
    expStr = expStr.replace('@WebUser.No', webUser.No);
    expStr = expStr.replace('@WebUser.Name', webUser.Name);
    expStr = expStr.replace("@WebUser.FK_DeptNameOfFull", webUser.FK_DeptNameOfFull);
    expStr = expStr.replace('@WebUser.FK_DeptName', webUser.FK_DeptName);
    expStr = expStr.replace('@WebUser.FK_Dept', webUser.FK_Dept);
    if (expStr.indexOf('@') == -1)
        return expStr;

    var objs = document.all;
    for (var i = 0; i < objs.length; i++) {

        if (expStr.indexOf('@') == -1)
            return expStr;

        var obj = objs[i].tagName;
        if (obj == null)
            continue;


        //把标签名转换为小写
        obj = obj.toLowerCase();
        if (obj != "input" && obj != "select")
            continue;
        //获取节点的ID 和值
        var NodeID = objs[i].getAttribute("id");
        if (NodeID == null)
            continue;
        var NodeType = objs[i].getAttribute("type");
        var NodeValue = "";
        if (obj != "input" && (NodeType == "text" || NodeType == "radio" || NodeType == "checkbox")) {
            NodeValue = objs[i].value;
            if (NodeType == "checkbox") {
                NodeValue = 0;
                var isChecked = NodeID.is(":checked");
                if (isChecked == true)
                    NodeValue = 1;
            }
            if (NodeType == "radio") {
                var nodeName = objs[i].getAttribute("name");
                NodeValue = $("input:radio[name='" + nodeName + "']:checked").val();
            }

        } else if (obj == "select") {
            NodeValue = decodeURI(objs[i].value);
        }
        expStr = expStr.replace("@" + NodeID.substring(NodeID.indexOf("_") + 1), NodeValue);
    }

    return expStr;
}


//获取WF之前路径
function GetLocalWFPreHref() {
    var url = window.location.href;
    if (url.indexOf('/WF/') >= 0) {
        var index = url.indexOf('/WF/');
        url = url.substring(0, index);
    } else {
        url = "";
    }
    return url;
}
function validate(s) {
    if (s == null || typeof s === "undefined") {
        return false;
    }
    s = s.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
    if (s == "" || s == "null" || s == "undefined") {
        return false;
    }
    return true;
}
function GetPKVal(params) {

    var val = params.OID;

    if (val == undefined || val == "")
        val = params.No;

    if (val == undefined || val == "")
        val = params.WorkID;

    if (val == undefined || val == "")
        val = params.NodeID;

    if (val == undefined || val == "")
        val = params.MyPK;

    if (val == undefined || val == "")
        val = params.PKVal;

    if (val == undefined || val == "")
        val = params.PK;

    if (val == "null" || val == "" || val == undefined)
        return null;

    return val;
}
export{
    GenerCheckNames,//获取所有的复选框的name值
    InitDDLOperation,//Select下拉框的Option解析
    ConvertDefVal,//获取表单的字段的值
    checkBlanks,//是否必填
    checkReg,//正则表单式
    setEnable,//枚举字段的联动
    SetCtrlVal,
    CleanCtrlVal,
    GenerBindDDL,
    DealExp,//替换字段内容
    GetLocalWFPreHref,//获取前台页面的地址
    validate,
    GetPKVal
 
}
